<?php
/**
 * Create by 11li
 * Date 2020/3/6
 * Time 10:52
 *
 */

namespace app\common\service;


use app\common\model\Commission;
use app\common\model\Funds;
use app\common\model\Goods;
use app\common\model\Promoter;
use app\common\model\PromoterCount;
use app\common\model\User;
use think\Db;
use think\Exception;

class CommissionService extends BaseService
{
	public function __construct()
	{
		$this->model = new Commission();
	}
	
	public function addShareCommission($viewUserId, $shareUserId, $goodsId)
	{
		if(!$viewUserId || !$shareUserId || !$goodsId || $viewUserId == $shareUserId) {
			$this->error = '参数错误';
			return false;
		}
		
		$promoter = Promoter::get(['user_id' => $shareUserId, 'status' => StatusService::STATUS_NORMAL]);
		if(!$promoter) {
			return true;
		}
		
		$row = $this->model
			->where([
				'user_id' => $shareUserId,
				'type' => StatusService::COMMISSION_TYPE_VIIEW,
				'relation_user_id' => $viewUserId,
				'goods_id' => $goodsId])
			->find();
		if($row) {
			$this->error = '已添加过浏览佣金了';
			return false;
		}
		
		$goods = Goods::get($goodsId);
		if($goods['status'] == StatusService::STATUS_NORMAL && $goods['view_commission'] > 0) {
			$this->model->startTrans();
			try {
				$res = $this->model->addRecord($shareUserId, $goodsId, $goods['view_commission'], $viewUserId, '', '', StatusService::COMMISSION_TYPE_VIIEW, StatusService::COMMISSION_STATUS_SEND, '浏览佣金');
				
				if(!$res) {
					throw new Exception('添加佣金记录出错'.$this->model->getLastSql());
				}
				
				$user = User::get($shareUserId);
				$funds = new FundsService();
				$fundsRes = $funds->addRecord($shareUserId, $goods['view_commission'], $user['money'], Funds::ACCOUNT_TYPE_BALANCE, Funds::OPE_TYPE_PLUS, Funds::TYPE_VIEW_COMISSION, '', '', $viewUserId);
				if(!$fundsRes) {
					throw new Exception('添加资金记录出错');
				}
				
				$countModel = new PromoterCountService();
				$countRes = $countModel->addCommission($shareUserId, $goodsId, 1, 0, 0, 0, $goods['view_commission']);
				if(!$countRes) {
					throw new Exception('添加推广商品佣金统计出错');
				}
				
				$userRes = Db::name('user')
					->where(['id' => $shareUserId])
					->setInc('money', $goods['view_commission']);
				
				if(!$userRes) {
					throw new Exception('添加用户余额出错');
				}
				
				$promoterRes = (new Promoter())
					->where(['id' => $promoter['id']])
					->setInc('commission', $goods['view_commission']);
				
				if(!$promoterRes) {
					throw new Exception('添加代理佣金总数出错');
				}
				$this->model->commit();
			} catch (Exception $e) {
				$this->model->rollback();
				$this->error = $e->getMessage();
				return false;
			}
		}
		
		return true;
	}
	
	
	/**
	 * 添加佣金记录
	 * @param $userId //用户ID
	 * @param $relationUserId //关联用户ID
	 * @param $orderId //订单ID
	 * @param $itemId //订单详情ID
	 * @param $goodsId //商品ID
	 * @param $amount //佣金
	 * @param int $type //佣金类型
	 * @param int $status // 佣金状态
	 * @param string $remark //备注信息
	 * @return int|string
	 */
	public static function addRecord($userId, $relationUserId, $orderId, $itemId, $goodsId, $amount, $type = StatusService::COMMISSION_TYPE_ORDER, $status = StatusService::COMMISSION_STATUS_WAIT, $remark = '') {
		$data = [
			'user_id' => $userId,
			'relation_user_id' => $relationUserId,
			'order_id' => $orderId,
			'order_goods_id' => $itemId,
			'goods_id' => $goodsId,
			'amount' => $amount,
			'type' => $type,
			'remark' => $remark,
			'status' => $status,
			'create_time' => time(),
			'update_time' => time()
		];
		
		return Db::name('commission')->insert($data);
	}
}